package com.zhugy.comparecode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.zhugy.comparecode.util.CommonUtils;

public abstract class BaseCodeFile implements CodeFile {

	private String fullName;

	private String simpleName;

	private String directory;

	private String relativeName;

	private List<CodeLine> codeLines;
	
	protected boolean isInMultiLineComment;

	public BaseCodeFile(String baseDir, String relativePath) {
		this.fullName = CommonUtils.concatPath(baseDir, relativePath);
		this.relativeName = CommonUtils.replace(relativePath, "\\", "/");
		this.directory = CommonUtils.extractDirectory(fullName);
		this.simpleName = CommonUtils.extractSimpleName(fullName);
		this.codeLines = parseCodeLines();
	}

	private List<CodeLine> parseCodeLines() {
		List<CodeLine> codeLines = new ArrayList<>();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(this.fullName));
			int l = 0;
			String line;
			while ((line = br.readLine()) != null) {
				l++;
				String lineAfterTrim = CommonUtils.trim(line);
				if (isBlankLine(lineAfterTrim)) {
					updateInMultiLineComment(lineAfterTrim);
					continue;
				}
				
				CodeLine codeLine = parseLineWithContent(lineAfterTrim, l);
				codeLines.add(codeLine);
				updateInMultiLineComment(lineAfterTrim);
			}
		} catch (Exception e) {
			throw new RuntimeException("解析行数出错！！", e);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return codeLines;
	}

	protected void updateInMultiLineComment(String lineAfterTrim) {
		
	}

	protected abstract CodeLine parseLineWithContent(String content, int index);

	protected abstract boolean isBlankLine(String content);

	@Override
	public String simpleName() {
		return simpleName;
	}

	@Override
	public String name() {
		return fullName;
	}

	@Override
	public String directory() {
		return directory;
	}

	@Override
	public String relativeName() {
		return getShowName();
	}

	@Override
	public List<CodeLine> lines() {
		return codeLines;
	}

	public String getShowName() {
		if (!CommonUtils.isEmpty(this.relativeName)) {
			return this.relativeName;
		} else {
			return this.simpleName;
		}
	}

}
